package com.xjj.gateway.filter;

import com.xjj.entity.Manager;
import com.xjj.entity.Parent;
import com.xjj.entity.ResponseEntity;
import com.xjj.util.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.xjj.util.utils.RedisConstants.*;

/**
 * @author : 王泰元
 * @date : 2022/10/21 11:43
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String uri = request.getURI().toString();
        // 如果该路径无需拦截
        if (!FilterUtils.needFilter(uri)) {
            log.debug("LoginFilter >>>>>>>>>> uri : {} >>>>>>>>>> 直接放行路径", uri);
            // 追加请求头，标识该路径在所有过滤器中都可以直接放行
            request.mutate().header("release", "true").build();
            return chain.filter(exchange);
        }

        // 返回未登录响应 401
        ResponseEntity<Object> responseEntity = ResponseEntity.UNAUTHORIZED("未登录", null);
        // 请求头中的 token
        String token = request.getHeaders().getFirst("token");
        log.debug("LoginFilter >>>>>>>>>> token : {}", token);
        // token 非法
        if (!StringUtils.hasLength(token) || !JwtUtil.verifyJWT(token)) {
            log.debug("LoginFilter >>>>>>>>>> uri : {} xxxxxxxxxxx token 不存在，或token非法", uri);
            return FilterUtils.getResult(exchange, responseEntity);
        }

        String key = uri.contains("/admin") ? LOGIN_TOKEN_ADMIN_KEY + token : LOGIN_TOKEN_API_KEY + token;
        Object o = redisTemplate.opsForValue().get(key);

        // 再次校验 redis 中的 token
//        if (uri.contains("/admin")) {
//            key = LOGIN_TOKEN_ADMIN_KEY + token;
//            Manager manager = (Manager) redisTemplate.opsForValue().get(key);
//            if (manager == null) {
//                log.debug("LoginFilter >>>>>>>>>> admin >>>>>>>>>> redis 不存在 token");
//                return FilterUtils.getResult(exchange, ResponseEntity.UNAUTHORIZED("未登录或登录已失效", null));
//            } else {
//                // 刷新过期时间
//                redisTemplate.opsForValue().set(key, manager, LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
//            }
//        }else if (uri.contains("/api")){
//            key=LOGIN_TOKEN_API_KEY + token;
//            Parent parent = (Parent) redisTemplate.opsForValue().get(key);
//            if (parent == null) {
//                log.debug("LoginFilter >>>>>>>>>> api >>>>>>>>>> redis 不存在 token");
//                return FilterUtils.getResult(exchange, ResponseEntity.UNAUTHORIZED("未登录或登录已失效", null));
//            } else {
//                // 刷新过期时间
//                redisTemplate.opsForValue().set(key, parent, LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
//            }
//        }

        // 放行
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
